package org.thirdHero.admin.web;

import com.alibaba.druid.util.StringUtils;
import org.thirdHero.admin.annotation.LoginAdmin;
import org.thirdHero.core.enums.MenuStatus;
import org.thirdHero.core.util.ResponseUtil;
import org.thirdHero.db.domain.SysMenu;
import org.thirdHero.db.domain.SysUser;
import org.thirdHero.db.service.SysMenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/admin/menu")
public class MenuController {
    private static final Logger logger = LoggerFactory.getLogger(MenuController.class);
    @Autowired
    private SysMenuService sysMenuService;

    @GetMapping("/list")
    public Object list(@LoginAdmin SysUser sysUser ,
                       String name,
                       @RequestParam(value = "page",defaultValue = "1")Integer page,
                       @RequestParam(value = "limit",defaultValue = "10")Integer limit,
                       String sort,String order){
        List<SysMenu> sysMenus = sysMenuService.querySelective(name, page, limit, sort, order);
        int total = sysMenuService.countSeletive(name, page, limit, sort, order);
        HashMap<String, Object> data = new HashMap<>();
        data.put("total",total);
        data.put("items", sysMenus);
        return ResponseUtil.ok(data);
    }
    @PostMapping("/checkExistUrl")
    public Object checkExistUrl(@LoginAdmin SysUser sysUser ,
                                @RequestBody SysMenu menu){
        if (StringUtils.isEmpty(menu.getUrl())) {
            return ResponseUtil.fail();
        }else{
            List<SysMenu> sysMenus = this.sysMenuService.checkExistUrl(menu.getUrl());
            Map<String, Object> data = new HashMap<String, Object>();
            if (!(sysMenus !=null && !sysMenus.isEmpty())) {
                data.put("errno", 1);
                data.put("errmsg", "校验通过");
                return ResponseUtil.ok(data);
            }else{
                data.put("errno", -1);
                data.put("errmsg", "校验未通过");
                return ResponseUtil.ok(data);
            }
        }
    }
    @GetMapping("/menuTest")
    @ResponseBody
    public Object menuTest(){
        String s = "[{path:'/user',component:Layout,redirect:'noredirect',name:'userManage',meta:{title:'用户管理',icon:'chart'},children:[{path:'user',component:_import('user/user'),name:'user',meta:{title:'会员管理',noCache:true}},{path:'address',component:_import('user/address'),name:'address',meta:{title:'收货地址',noCache:true}},{path:'collect',component:_import('user/collect'),name:'collect',meta:{title:'会员收藏',noCache:true}},{path:'footprint',component:_import('user/footprint'),name:'footprint',meta:{title:'会员足迹',noCache:true}},{path:'history',component:_import('user/history'),name:'history',meta:{title:'搜索历史',noCache:true}},{path:'cart',component:_import('user/cart'),name:'cart',meta:{title:'购物车',noCache:true}}]},{path:'/mall',component:Layout,redirect:'noredirect',name:'mallManage',meta:{title:'商场管理',icon:'chart'},children:[{path:'region',component:_import('mall/region'),name:'region',meta:{title:'行政区域',noCache:true}},{path:'brand',component:_import('mall/brand'),name:'brand',meta:{title:'品牌制造商',noCache:true}},{path:'category',component:_import('mall/category'),name:'category',meta:{title:'商品类目',noCache:true}},{path:'order',component:_import('mall/order'),name:'order',meta:{title:'订单管理',noCache:true}},{path:'issue',component:_import('mall/issue'),name:'issue',meta:{title:'通用问题',noCache:true}},{path:'keyword',component:_import('mall/keyword'),name:'keyword',meta:{title:'关键词',noCache:true}}]},{path:'/goods',component:Layout,redirect:'noredirect',name:'goodsManage',meta:{title:'商品管理',icon:'chart'},children:[{path:'goods',component:_import('goods/goods'),name:'goods',meta:{title:'商品管理',noCache:true}},{path:'attribute',component:_import('goods/attribute'),name:'attribute',meta:{title:'商品参数',noCache:true}},{path:'specification',component:_import('goods/specification'),name:'specification',meta:{title:'商品规格',noCache:true}},{path:'product',component:_import('goods/product'),name:'product',meta:{title:'货品管理',noCache:true}},{path:'comment',component:_import('goods/comment'),name:'comment',meta:{title:'用户评论',noCache:true}}]},{path:'/promotion',component:Layout,redirect:'noredirect',name:'promotionManage',meta:{title:'推广管理',icon:'chart'},children:[{path:'ad',component:_import('promotion/ad'),name:'ad',meta:{title:'广告列表',noCache:true}},{path:'topic',component:_import('promotion/topic'),name:'topic',meta:{title:'专题管理',noCache:true}}]},{path:'/sys',component:Layout,redirect:'noredirect',name:'sysManage',meta:{title:'系统管理',icon:'chart'},children:[{path:'admin',component:_import('sys/admin'),name:'admin',meta:{title:'管理员',noCache:true}},{path:'os',component:_import('sys/os'),name:'os',meta:{title:'对象存储',noCache:true}},{path:'menu',component:_import('sys/menu'),name:'menu',meta:{title:'菜单管理',noCache:true}},{path:'treeMenu',component:_import('sys/treeMenu'),name:'treeMenu',meta:{title:'树形菜单',noCache:true}},{path:'role',component:_import('sys/role'),name:'role',meta:{title:'角色管理',noCache:true}},{path:'dept',component:_import('sys/dept'),name:'dept',meta:{title:'部门管理',noCache:true}},{path:'userMangaer',component:_import('sys/userManager'),name:'userManager',meta:{title:'系统用户管理',noCache:true}}]},{path:'*',redirect:'/404',hidden:true}]";
        return ResponseUtil.ok(s);
    }
    @GetMapping("/{pCode}")
    @ResponseBody
    public Object findMenuById(@LoginAdmin SysUser sysUser ,@PathVariable String pCode){
        List<SysMenu> liteMallMenuByCode = this.sysMenuService.findLiteMallMenuByCode(pCode);
        if (liteMallMenuByCode!=null && !liteMallMenuByCode.isEmpty()) {
            return ResponseUtil.ok(liteMallMenuByCode.get(0));
        }else{
            return ResponseUtil.fail(-1,"没有该节点信息");
        }
    }
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public Object deleteMenuTree(@LoginAdmin SysUser sysUser ,@PathVariable String id){
        SysMenu liteMallMenu = this.sysMenuService.findLiteMallMenuById(Integer.parseInt(id));
        if(liteMallMenu !=null){
            List<SysMenu> liteMallMenuChild = this.sysMenuService.findChildLitemallMenu(liteMallMenu.getCode());
            if(liteMallMenuChild!=null && !liteMallMenuChild.isEmpty()){
                return ResponseUtil.fail(-1,"该菜单下有子菜单，请删除所有子菜单后重试！");
            }else{
                int result = this.sysMenuService.deleteLitemallMenuById(liteMallMenu.getId());
                if(result == 1){
                    return ResponseUtil.ok("删除成功");
                }else{
                    return ResponseUtil.fail(-1,"删除失败请重试");
                }
            }
        }else{
            return ResponseUtil.fail(-1,"该菜单不存在无法删除");
        }
    }
    @PutMapping("/editMenu/{id}")
    @ResponseBody
    public Object editMenu(@LoginAdmin SysUser sysUser , @RequestBody SysMenu sysMenu, @PathVariable String id){
        SysMenu liteMallMenuById = this.sysMenuService.findLiteMallMenuById(Integer.parseInt(id));
        if(liteMallMenuById!=null){
            List<SysMenu> liteMallMenuByCode = this.sysMenuService.findLiteMallMenuByCode(sysMenu.getCode());
            if(!sysMenu.getCode().equals(liteMallMenuById.getCode())){//code不相等时需要校验是否已存在该code
                if(liteMallMenuByCode!=null && !liteMallMenuByCode.isEmpty()){
                    return ResponseUtil.errorBussiness("该菜单已存在");
                }
            }
            sysMenu.setId(liteMallMenuById.getId());
            menuSetPcode(sysMenu);
            if(sysMenu.getCode().equals(sysMenu.getPcode())){
                return ResponseUtil.fail(-1,"不能将自己添加为父节点");
            }
            int result = this.sysMenuService.updateLiteMallById(sysMenu);
            if(result == 1){
                return ResponseUtil.ok("更新成功");
            }else{
                return ResponseUtil.fail(-1,"更新失败请重试");
            }
        }else{
            return ResponseUtil.fail(-1,"没有找到要修改的菜单信息");
        }
    }
    @PostMapping("/create")
    @ResponseBody
    public Object addMenuTree(@LoginAdmin SysUser sysUser ,@RequestBody SysMenu sysMenu){
        List<SysMenu> liteMallMenuByCode = this.sysMenuService.findLiteMallMenuByCode(sysMenu.getCode());
        if(liteMallMenuByCode!=null && !liteMallMenuByCode.isEmpty()){
            return ResponseUtil.errorBussiness("该菜单已存在");
        }else{
            menuSetPcode(sysMenu);
            sysMenu.setStatus(MenuStatus.ENABLE.getCode());
            logger.info("保存菜单信息");
            this.sysMenuService.inserLiteMallMenu(sysMenu);
            return ResponseUtil.ok("保存成功");
        }
    }

    @GetMapping("/queryMenuTree")
    @ResponseBody
    public Object queryMenuTree(@RequestParam(required = false) String name){
        List<SysMenu> menus;
        if(StringUtils.isEmpty(name) || "".equals(name)){
            menus = this.sysMenuService.findChildLitemallMenu("top");
        }else{
            menus = this.sysMenuService.queryLiteMallByName(name);
        }
        if(menus!=null && !menus.isEmpty()){
            for(SysMenu itemMenus:menus){
               getChild(itemMenus);
            }
        }
        HashMap<String,Object> data = new HashMap<>();
        data.put("items",menus);
        data.put("total", menus != null ? menus.size() : 0);
        return ResponseUtil.ok(data);
    }
    public List<SysMenu> getChild(SysMenu sysMenu){
        List<SysMenu> sysMenus = sysMenuService.findChildLitemallMenu(sysMenu.getCode());
        if (sysMenus !=null && !sysMenus.isEmpty()) {
            sysMenu.getChildren().addAll(sysMenus);
        }else{
            sysMenu.setChildren(null);
        }
        for (int i = 0; i < sysMenus.size(); i++) {
            SysMenu sysMenu1 = sysMenus.get(i);
            getChild(sysMenu1);
        }
        if(sysMenus.size()==0){
            return null;
    }
        return sysMenus;
    }
    private void menuSetPcode(SysMenu menu){
        if(StringUtils.isEmpty(menu.getPcode())){
            menu.setPcode("0");
            menu.setPcodes("[0],");
            menu.setLevels(1);
        }else {
            SysMenu PMenu = this.sysMenuService.findLiteMallMenuById(Integer.parseInt(menu.getPcode()));
            if(PMenu!=null ){
                Integer pLevel = PMenu.getLevels();
                menu.setPcode(PMenu.getCode());
                menu.setLevels(pLevel + 1);
                menu.setPcodes(PMenu.getPcodes() + "[" + PMenu.getCode() + "],");
            }
        }
    }
}
